module.exports = app => {
    const express = require('express')
    const Specialty = require('../../models/Specialty')
    const Department = require(`../../models/Department`)
    const Teacher = require('../../models/Teacher')
    const User = require('../../models/User')
    const Student = require('../../models/Student')
    const Grade = require('../../models/Grade')
    const College = require('../../models/College')
    const Class = require('../../models/Class')
    const Course = require('../../models/Course')
    const AdminUser = require("../../models/AdminUser")
    const auth = require('../../middleware/auth')
    const fs = require("fs")
    const router = express.Router({
        mergeParams: true
    })
    //通用的曾加
    router.post('/', async (req, res) => {
        //TODO:这里，改成查数据库里面最后一个数据的编号，然后++,就不要操作配置文件了
        const noObject = require('../../config/numbe.json'); //导入配置文件，default是默认初始，nowNum是现如今编号
        const inInfo = req.body //inInfo是向数据库写入的数据，先是用它接收传过来的不带nid的参数
        let nowNum = noObject[req.params.resource] //先给nowNum对应的默认编号，这里如果是没配置的，可能就会出现UNDEFIEND
        req.Model.find({}, (err, result) => {
            if (err) {
                return res.json({
                    success: false,
                    message: err
                })
            }
            let cantLike = [] //这里是一个列表，里面放着判断是否重复的字段
            //去重判断
            if (req.Model.modelName == "Class") {
                cantLike.push('name')
            }
            if (req.Model.modelName == 'AdminUser') {
                cantLike.push("username")
            }
            if (cantLike.length > 0) {
                //对去重列表进行循环
                for (let i = 0; i < cantLike.length; i++) {
                    for (let z = 0; z < result.length; z++) {
                        //对结果列表进行循环
                        if (result[z][cantLike[i]] == inInfo[cantLike[i]]) {
                            //如果有相同的
                            return res.json({
                                success: false,
                                message: '该信息已经存在'
                            })
                        }
                    }
                }
            }
            //如果配置中有的话，就给nid
            if (result.length > 0 && nowNum) {
                //结果大于0，说明有了，就从最后一个的nid赋值给nowNum
                nowNum = result[result.length - 1].nid;
                lastNum = parseInt(nowNum.slice(2)) + 1;
                fitstNum = nowNum.slice(0, 2);
                inInfo.nid = fitstNum + lastNum
            } else if (result.length == 0 && nowNum) {
                //结果等于0的话，就赋值默认值
                inInfo.nid = nowNum
            }
            req.Model.create(inInfo, function (err, ress) {
                if (err) {
                    return res.json({
                        success: false,
                        message: err
                    })
                }
                return res.json({
                    success: true,
                    message: "添加成功！"
                })
            })
        })
    })
    //通用的查找
    router.get('/', async (req, res) => {
        const queryOptions = {}
        if (req.Model.modelName === "Specialty" || req.Model.modelName === "Class") {
            queryOptions.populate = 'superior'
        }
        let params = req.query;
        let mp = {} //条件查询参数;
        for (let i in params) {
            if (params[i] !== undefined && i != 'size' && i != 'page' && params[i] && params[i] != "''") {
                mp[i] = params[i]
            }
        }
        const model = await req.Model.find({
            ...mp
        }).setOptions(queryOptions);
        res.send(model)
    })
    //通用的通过id查找
    router.get('/:id', async (req, res) => {
        const queryOptions = {}
        if (req.Model.modelName == "Student") {
            queryOptions.populate = [{
                path: 'class',
                select: ['name', 'nid']
            }, {
                path: 'specialty',
                select: ['name', 'nid'],
                populate: {
                    path: 'superior',
                    select: ['name', 'nid'],
                    populate: {
                        path: 'superior',
                        select: ['name', "nid"]
                    }
                }
            }]
        }
        if (req.Model.modelName == "Teacher") {
            queryOptions.populate = [{
                path: 'department',
                select: ['name', 'nid'],
                populate: {
                    path: 'superior',
                    select: ['name', 'nid']
                }
            }]
        }
        if (req.Model.modelName == 'Course') {
            queryOptions.populate = [{
                path: 'teacher',
                select: ['name', 'nid'],
            }, {
                path: 'specialty',
                select: ['name', 'nid'],
            }, {
                path: 'class',
                select: ['name', 'nid'],
            }]
        }
        const model = await req.Model.findById(req.params.id).setOptions(queryOptions);
        res.send(model)
    })
    //通用的删除
    router.delete('/:id', async (req, res) => {
        req.Model.find((err, result) => {
            if (err) {
                return res.json({
                    success: false,
                    message: err
                })
            }
            if (result.length == 1) {
                return res.json({
                    success: false,
                    message: '最后一个无法被删除！'
                })
            }
            if (req.Model.modelName == "Teacher" || req.Model.modelName == "Student") {
                User.deleteOne({
                    "bindId": req.params.id
                }, (err, result) => {
                    if (err) {
                        return res.json({
                            success: false,
                            message: err
                        })
                    }
                    req.Model.findByIdAndDelete(req.params.id, (err, result) => {
                        if (err) {
                            return res.json({
                                success: false,
                                message: err
                            })
                        }
                        return res.json({
                            success: true,
                            message: '删除成功！'
                        })
                    })
                })
            } else if (req.Model.modelName == 'Course') {
                Grade.find({
                    course: req.params.id
                }, (err, result) => {
                    if (err) {
                        return res.json({
                            success: false,
                            message: err
                        })
                    }
                    Grade.deleteMany({
                        _id: {
                            $in: result
                        }
                    }, (err, result) => {
                        if (err) {
                            return res.json({
                                success: false,
                                message: err
                            })
                        }
                        req.Model.findByIdAndDelete(req.params.id, (err, result) => {
                            if (err) {
                                return res.json({
                                    success: false,
                                    message: err
                                })
                            }
                            return res.json({
                                success: true,
                                message: '删除成功！'
                            })
                        })
                    })
                })
            } else {
                req.Model.findByIdAndDelete(req.params.id, (err, result) => {
                    if (err) {
                        return res.json({
                            success: false,
                            message: err
                        })
                    }
                    return res.json({
                        success: true,
                        message: '删除成功！'
                    })
                })
            }
        })
    })
    //通用的通过id更新
    router.put('/:id', async (req, res) => {
        //如果是Course
        if (req.Model.modelName == "Course") {
            let courseId = await req.Model.findById(req.params.id, {
                class: 1
            })
            //班级被改变了

            if (req.body.class != courseId.class) {
                let t = await Grade.deleteMany({
                    course: req.params.id
                })
              
                let studentList = await Student.find({
                    class: req.body.class
                }, {
                    _id: 1
                });
               
                let inputStudentList = []

                for (let i = 0; i < studentList.length; i++) {
                    inputStudentList.push({
                        grade: 0,
                        course: req.params.id,
                        student: studentList[i]._id,
                        xf: 0,
                        gpa: 0,
                        isEdit: false
                    })
                }
               

                let e = await Grade.insertMany(inputStudentList)
                //TODO:添加进Grade表中
            }
        }
        //如果更改的是成绩的话
        if (req.Model.modelName == "Grade") {
            let courseInfo = await Course.findById(req.body.course, {
                zxf: 1,
                zjd: 1
            });
            //TODO:这里写成绩改变时候的操作了!!!!管理员端终于要完结了，撒花
            // let Grade = await Grade.findById(req.params.id);          
            let xf = courseInfo.zxf;
            let jd = parseInt(courseInfo.zjd) * parseInt(req.body.grade) / 100;
            req.body.xf = xf;
            req.body.gpa = jd;
        }
        let model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
        if (model) {
            return res.json({
                success: true,
                message: '编辑成功！'
            })
        } else {
            return res.json({
                success: true,
                message: '编辑失败！'
            })
        }
    })

    app.use('/admin/api/rest/:resource', auth(), async (req, res, next) => {
        req.Model = require(`../../models/${req.params.resource}`)
        next()
    }, router)
    /*------------给出进来用户的名字---------------*/
    app.get('/admin/api/UserAPI/getUsername', auth(), async (req, res) => {
        //这里id已经在auth中获得了，所以我们可以直接拿
        if (req.user.identity == 2) {
            res.send({
                username: req.user.username+'管理员'
            })
        } else {
            const {
                bindId,
                identity
            } = req.user;
            if (identity == 0) {
                let studentRes = await Student.findById(bindId);
                res.send({
                    username: studentRes.name+'同学'
                })
            } else if (identity == 1) {
                let teacherRes = await Teacher.findById(bindId);
                res.send({
                    username: teacherRes.name+'老师'
                })
            }
        }
        // if(req.user.identity==0){

        // }
    })

    /*------------------上面是公共接口部分，简单的增删改查--------------------------*/
    /*------------这里是获取分页列表的公共接口部分------------*/
    /**-----------查询列表的接口----------------------------------**/
    require('./handleList')(app)

    /*------------------多次插入的公共接口------------------------------*/
    require('./handleRestInsertMany')(app)

    /*------------------这个是插入课表的接口，插入课表之后，会同时生成成绩-------------------------*/
    require('./handleInsertCourse')(app)

    /*------------------下面是特定接口，需要完成一些特定操作，简单的增删改查--------------------------*/
    require('./handleSpeciltyThing')(app)

    /***********************登录接口**************************************/
    require('./login')(app)
    /*------------------------教师端接口-------------------------------*/ 
    require('../teacher')(app)
    /*-------------------------学生端接口---------------*/
    require('../student')(app)
    /***********************测试用接口**************************************/
    require('./testApi')(app)

    //错误处理函数
    app.use(async (err, req, res, next) => {
        res.status(err.statusCode).send({
            message: err.message
        })
    })
    /*
        多条添加原代码:
         req.Model.find().exec(async (err, doc) => {
            if (err) {
                return res.json({
                    success: false,
                    message: err
                })
            }
            //将一段长的数组，进行json转换
            let isContinue = true;
            if (req.Model.modelName == "Teacher" || req.Model.modelName == "Student") {
                let jsDoc = JSON.stringify(doc)
                for (let i = 0; i < req.body.length; i++) {
                    if (jsDoc.indexOf(req.body[i].nid) != -1 || jsDoc.indexOf(req.body[i].identity) != -1) {
                        //然后在这个json字符串中查找对应的字段
                        isContinue = false;
                        return res.json({
                            success: false,
                            message: `第${i+1}行信息已经存在，请勿多次添加！`
                        })
                    }
                    if (req.Model.modelName == "Student") {
                        let classRes = await Class.findById(req.body[i].class)
                        req.body[i].class = classRes._id
                        let specialtyRes = await Specialty.findById(req.body[i].specialty)
                        req.body[i].specialty = specialtyRes._id;
                    } else if (req.Model.modelName == "Teacher") {
                        let departmentRes = await Department.findById(req.body[i].department)
                        req.body[i].department = departmentRes._id;
                    }
                }

            }
            if (req.Model.modelName == "Class") {
                let jsDoc = JSON.stringify(doc)
                for (let i = 0; i < req.body.length; i++) {
                    if (jsDoc.indexOf(req.body[i].nid) != -1 || jsDoc.indexOf(req.body[i].name) != -1) {
                        //然后在这个json字符串中查找对应的字段
                        isContinue = false;
                        return res.json({
                            success: false,
                            message: `第${i+1}行信息已经存在，请勿多次添加！`
                        })
                    }
                    let superiorRes = await Specialty.findById(req.body[i].superior)
                    req.body[i].superior = superiorRes._id
                }
            }

            if (isContinue) {
                req.Model.collection.insert(req.body, (err, doc) => {
                    if (err) {
                        res.send({
                            success: false,
                            message: err
                        })
                    }
                    //只有老师和教师的批量插入，才有用户的增加
                    if (req.Model.modelName == "Teacher" || req.Model.modelName == "Student") {
                        let userList = []
                        let identity = "0";
                        if (req.Model.modelName == "Teacher") {
                            identity = "1";
                        }
                        for (let i = 0; i < doc.ops.length; i++) {
                            let useInfo = {
                                username: doc.ops[i].nid,
                                bindId: doc.ops[i]._id,
                                identity: identity,
                                password: "123456",
                            }
                            userList.push(useInfo)
                        }
                        User.collection.insert(userList, (err, doc) => {
                            if (err) {
                                res.send({
                                    success: false,
                                    message: err
                                })
                            }
                            res.send({
                                success: true,
                                message: '数据导入成功！'
                            })
                        })
                    } else {
                        res.send({
                            success: true,
                            message: '数据导入成功！'
                        })
                    }
                })
            }
        })
    */
    /*
         原来的查询列表
         slrouter.get('/', async (req, res) => {
         let limit = parseInt(req.query.size) || 10; //分页参数
         let currentPage = parseInt(req.query.page) || 1; //当前页码
         let params = req.query;
         let mp = {} //条件查询参数
         const queryOptions = {} //要关联其他表的时候的配置
         if (req.Model.modelName === "Teacher") {
             queryOptions.populate = 'department'
         }
         if (req.Model.modelName === "Class") {
             queryOptions.populate = 'superior'
         }
         if (req.Model.modelName == "Student") {
             queryOptions.populate = [{
                 path: "class",
                 select: ["_id", "name"]
             }, {
                 path: "specialty",
                 select: ["_id", "name"]
             }]
         }
         if (req.Model.modelName == 'User') {

         }
         if (currentPage < 1) {
             currentPage = 1;
         }
         if (limit < 1) {
             limit = 1;
         }
         req.Model.find({}, (err, ress) => {
             if (err) return res.json({
                 success: false,
                 message: err
             });
             let all = ress.length;
             req.Model.find().setOptions(queryOptions).exec(async (err, doc) => {
                 if (err) {
                     return res.json({
                         success: false,
                         message: err
                     });
                 }
                 let tempList = []
                 doc.forEach(item => {
                     let allNum = 0;
                     let forNum = 0;
                     for (let i in params) {
                         if (params[i] !== undefined && i != 'size' && i != 'page' && params[i] && params[i] != "''") {
                             allNum = allNum + 1;
                             if (req.Model.modelName == "Class") {
                                 if (i == 'class') {
                                     console.log(`itemId=>${item._id};;params=>${params[i]}`);

                                     if (item._id == params[i]) {
                                         forNum = forNum + 1;
                                     }
                                 } else if (i == "superior") {
                                     if (item[i]._id == params[i]) {
                                         forNum = forNum + 1;
                                     }
                                 } else {
                                     if (item[i] == params[i]) {
                                         forNum = forNum + 1;
                                     }
                                 }
                             } else {
                                 if (i == "department" || i == "specialty" || i == 'class' || i == "superior") {
                                     if (item[i]._id == params[i]) {
                                         forNum = forNum + 1;
                                     }
                                 } else {
                                     if (item[i] == params[i]) {
                                         forNum = forNum + 1;
                                     }
                                 }
                             }
                         }
                     }

                     if (forNum == allNum) {
                         tempList.push(item)
                     }
                 })
                 all = tempList.length;
                 let returnList = tempList.slice((currentPage - 1) * limit, (currentPage) * limit)
                 if (req.Model.modelName == 'User') {
                     let returnDoc = []
                     for (let i = 0; i < returnList.length; i++) {
                         let docs = ''
                         if (returnList[i].identity == 0) {
                             docs = await Student.findById(returnList[i].bindId)
                         } else if (returnList[i].identity == 1 || returnList[i].identity == 2) {
                             docs = await Teacher.findById(returnList[i].bindId);
                         }
                         let temp = {
                             name: docs.name,
                             username: returnList[i].username,
                             username: returnList[i].username,
                             bindId: returnList[i].bindId,
                             password: returnList[i].password,
                             identity: returnList[i].identity,
                             _id: returnList[i]._id
                         }
                         returnDoc.push(temp)
                     }
                     return res.json({
                         success: true,
                         message: "请求成功",
                         counts: all,
                         list: returnDoc
                     })
                 } else {
                     return res.json({
                         success: true,
                         message: "请求成功",
                         counts: all,
                         list: returnList
                     })
                 }
             })
         })
     })
    */
}